from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse
from myadmin import models
from django.contrib.auth.hashers import make_password, check_password


# Create your views here.

def index(request):
    # 获取所有的一级分类
    data = models.Cates.objects.filter(pid=0)
    # 获取当前一级下的二级分类
    for x in data:
        x.sub = models.Cates.objects.filter(pid=x.id)
    context = {'data':data}

    return render(request,'home/index.html',context)


# 列表
def goodslist(request):
    # 获取所有的一级分类
    # data = models.Cates.objects.filter(pid=0)
    # # 获取当前一级下的二级分类
    # for x in data:
    #     x.sub = models.Cates.objects.filter(pid=x.id)
    # context = {'data':data}

    # 接受id
    cid = request.GET.get('cid')
    # 获取当前二级分类的对象
    ob = models.Cates.objects.get(id=cid)
    ob.goodslist = models.Goods.objects.filter(cateid=ob).order_by(request.GET.get('orderby','id'))

    # 分配数据
    context = {'data':ob}

    # 加载模板
    return render(request,"home/list.html",context)


# 详情
def goodsinfo(request):
    
    # 接受商品id
    gid = request.GET.get('gid')
    
    # 根据商品id获取对象
    ob = models.Goods.objects.get(id=gid)

    # 分配数据
    context = {'data':ob}

  
    # 加载模板
    return render(request,"home/info.html",context)


# 登录
def login(request):

    if request.method =='GET':
        return render(request,"home/login.html")
    else:
        # 执行登录
        try:
            # 根据手机号获取拥户
            ob = models.Users.objects.get(phone=request.POST['phone'])
            # 对比密码是否正确
            res = check_password(request.POST['password'],ob.password)
            if res:
                # 用户名和密码匹配
                # 在session中存入登陆凭证
                request.session['vipUser'] = {'username':ob.username,'phone':ob.phone,'uid':ob.id}
                    # 登录时获取当前页的路径
                

                nextpath = request.GET.get('nextpath','/')
                print(nextpath)
                args = eval(request.GET.get('args','{}'))
                print(args)
                a = ''
                for k,v in args.items():
                    a += '&'+k+'='+v
                nexturl = nextpath+'?'+a
                # 调到首页
                return HttpResponse('<script>alert("登录成功");location.href="'+nexturl+'"</script>')
           # 密码错误
            else:
                pass
        except:
            # 用户不存在
            return HttpResponse('<script>alert("用户名或密码错误");location.href="'+reverse('home_login')+'"</script>')


# 退出
def logout(request):

    del request.session['vipUser']
    return HttpResponse("<script>alert('退出登录');location.href='" + reverse('home_login') + "';</script>")
    

# 注册
def register(request):
    if request.method == 'GET':

        return render(request,"home/register.html")
    else:
        # try:
            # 验证手机的验证码
            
        if request.POST['phone'] != request.session['msgcode']['phone'] or request.POST['code'] != request.session['msgcode']['code']:
            return HttpResponse('<script>alert("验证码不正确");location.href="'+reverse('home_register')+'"</script>')
        
        # 密码加密
        password = make_password(request.POST['password'], None, 'pbkdf2_sha256')       
      
        # 生产随机的用户名
        username = 'user'+str(request.POST['phone'])
        data = {'username':username,'phone':request.POST['phone'],'password':password}
        # 执行注册
        ob = models.Users(**data)
        ob.save()
        # 跳转登录页面
        return HttpResponse('<script>alert("注册成功.请登录");location.href="' + reverse('home_login') + '"</script>')
        # except:
        #     return HttpResponse('<script>alert("注册失败");location.href="' + reverse('home_register') + '"</script>')


# 验证手机
def checkphone(request):
    # 接受手机号
    phone = request.GET.get('phone')
    # 到数据库查询
    num = models.Users.objects.filter(phone=phone).count()
    if num:
        return JsonResponse({'error': 1, 'msg': '手机号码已存在'})
    else:
        return JsonResponse({'error': 0, 'msg': '手机号码不存在'})


# 发送验证吗
def sendmsg(request):
    #接口类型：互亿无线触发短信接口，支持发送验证码短信、订单通知短信等。
    #账户注册：请通过该地址开通账户http://user.ihuyi.com/register.html
    #注意事项：
    #（1）调试期间，请用默认的模板进行测试，默认模板详见接口文档；
    #（2）请使用 用户名 及 APIkey来调用接口，APIkey在会员中心可以获取；
    #（3）该代码仅供接入互亿无线短信接口参考使用，客户可根据实际需要自行编写；
      
    # import urllib2
    import urllib
    import urllib.request
    import json
    import random
    #用户名 查看用户名请登录用户中心->验证码、通知短信->帐户及签名设置->APIID
    account  = "C90838470" 
    #密码 查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
    password = "51bd75c1dcbab4d7165ffc3186e8fd85"
    # 接受注册页面提供的手机号
    mobile = request.GET.get('phone')
    # 随机验证码
    code = str(random.randint(1000,9999))
    print('++++++++++++++++++'+code+'++++++++++++++++++')
    # 把验证码存入session
    request.session['msgcode'] = {'phone':mobile,'code':code}
    text = "您的验证码是："+code+"。请不要把验证码泄露给其他人。"
    data = {'account': account, 'password' : password, 'content': text, 'mobile':mobile,'format':'json' }
    # 发起 请求
    req = urllib.request.urlopen(
        url= 'http://106.ihuyi.com/webservice/sms.php?method=Submit',
        data= urllib.parse.urlencode(data).encode('utf-8')
    )
    # 获取响应内容
    content =req.read()
    # 解析结果
    res = json.loads(content.decode('utf-8'))
    # print(res)
    return HttpResponse('aaaaaaa')


# 加入购物车
def cartadd(request):
    goods = models.Goods.objects.get(id=request.GET.get('gid'))
    user = models.Users.objects.get(id=request.session['vipUser']['uid'])
    num = int(request.GET.get('num'))

    # 检查当前的商品是否已存在
    res = models.Cart.objects.filter(goodsid=goods).filter(uid=user)

    if res.count():
        # 已存在,数量相加
        for v in res:
            v.num += num
            v.save()
    else:
        # 添加到数据库
        ob=models.Cart(goodsid=goods,uid=user,num=num)
        ob.save()
    return JsonResponse({'srror':0,'msg':"成功加入购物车"})

# 购物车列表
def cartindex(request):
    # 获取当前用户的购物车数据
    data = models.Cart.objects.filter(uid=request.session['vipUser']['uid'])
    
    # 分配数据
    context = {'data':data}
    # 加载页面
    return render(request,'home/cart.html',context)

# 修改购物车数量
def cartedit(request):
    # 购物车id 数量
    cartid = request.GET.get('cartid')
    num = request.GET.get('num')
    # 获取购物车对象
    print(cartid)
    ob = models.Cart.objects.get(id=cartid)
    ob.num = int(num)
    ob.save()
    # 运算小计价格
    totalprice = ob.num*ob.goodsid.price
    return JsonResponse({'error':0,'msg':'修改成功','totalprice':"{:.2f}".format(totalprice)})

# 删除购物车商品
def cartdel(request):
    sc = request.GET.get('sc')
   
    ob = models.Cart.objects.get(id=sc)
    ob.delete()
    return JsonResponse({'a':0})


# 订单确认
def orderconfirm(request):
    # return render(request,'home/confirm.html')

    # 接收cartids
    cartids = eval(request.GET.get('cartids'))
    # 获取对应的购物车数据
    data = models.Cart.objects.filter(id__in=cartids)
    # 获取所有的一级城市数据
    citys = models.Citys.objects.filter(level = 1)
    # 分配数据
    context = {'data':data,'citys':citys}
    # 加载模板
    return render(request,'home/confirm.html',context)


# 创建订单
def ordercreate(request):
    # 获取提交的订单数据
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')
    # print(data)
    # 添加订单
    # 获取当前用户对象
    user = models.Users.objects.get(id=request.session['vipUser']['uid'])
    # 获取地址信息
    addr = models.Address.objects.get(id=data['addressid'])
    sheng = models.Citys.objects.get(id=addr.sheng).name
    shi = models.Citys.objects.get(id=addr.shi).name
    xian = models.Citys.objects.get(id=addr.xian).name
    shdz = sheng+shi+xian+addr.info

    # 计算总价
    totalprice = 0
    cart = models.Cart.objects.filter(id__in=eval(data['cartids']))
    for x in cart:
        totalprice += x.num*x.goodsid.price

    # 准备订单数据
    orderdata = {"uid":user,'shr':addr.shr,'shdh':addr.shdh,'shdz':shdz,'buytype':data['buytype'],'wl':data['wl']}
    orderdata['totalprice'] = totalprice
    # 创建订单
    order = models.Order(**orderdata)
    order.save()
    # 生成订单详情
    for x in cart:
        obinfo = models.OrderInfo()
        obinfo.orderid = order
        obinfo.goodsid = x.goodsid.id
        obinfo.title = x.goodsid.title
        obinfo.pic_url = x.goodsid.pic_url
        obinfo.price = x.goodsid.price
        obinfo.num = x.num
        # 添加到订单详情
        obinfo.save()
        # 删除购物车中已下单的商品
        x.delete()
    # 跳转到支付
    return HttpResponse('<script>alert("订单创建成功,请支付");location.href="/order/buy/?orderid='+str(order.id)+'"</script>')



# 订单支付
def orderbuy(request):
    # 订单号
    orderid = request.GET.get('orderid')
    # print(orderid)
    return render(request,'home/ddzf.html')



# 返回城市数据
def getcitys(request):
    # 根据id获取下一级的城市数据，返回json
    data = models.Citys.objects.filter(upid=request.GET.get('id')).values()
    # 解析json 返回
    return JsonResponse(list(data),safe=False)


# 添加地址
def addressadd(request):
    # 接收地址信息
    data = request.GET.dict()
    # 获取当前用户对象
    data['uid'] = models.Users.objects.get(id=request.session['vipUser']['uid'])
    # 进行数据存储
    ob = models.Address(**data)
    ob.save()
    # 返回结果
    return JsonResponse({'aa':1})


# 收货地址获取
def addresslist(request):
    try:
        # 获取当前用户的所有收货地址
        data = models.Address.objects.filter(uid=request.session['vipUser']['uid']).exclude(isChecked=2).values()
        for x in data:
            x['sheng'] = models.Citys.objects.get(id=x['sheng']).name
            x['shi'] = models.Citys.objects.get(id=x['shi']).name
            x['xian'] = models.Citys.objects.get(id=x['xian']).name
        # 返回数据
        return JsonResponse({'error':0,'data':list(data)},safe=False)
    except:
        return JsonResponse({'error':1,'msg':'尚无地址'})


# 个人中心我的订单
def orderinfo(request):
    # 获取当前用户
    user = models.Users.objects.get(id=request.session['vipUser']['uid'])
    # 分配数据
    ob = models.Order.objects.filter(uid=user)
    oc = models.Order.objects.filter(uid=user,status=0)
    od = models.Order.objects.filter(uid=user,status=1)
    oe = models.Order.objects.filter(uid=user,status=2)
    context = {'order':ob,'order0':oc,'order1':od,'order2':oe}
    # 加载模板
    return render(request,'home/orderinfo.html',context)


# 默认地址
def addrmoren(request):
    # 获取默认的id
    mr = request.GET.get('mr')
   
    ob = models.Address.objects.all()
    for x in ob:
        if x.isChecked !=2:
            x.isChecked=0
            x.save()
    oa = models.Address.objects.get(id=mr)
    oa.isChecked=1
    oa.save()
    return JsonResponse({'a':0})


# 删除地址
def dzsc(request):
    # 获取要删除的id值
    sc = request.GET.get('sc')

    ob = models.Address.objects.get(id=sc)
    ob.isChecked=2
    ob.save()
    return JsonResponse({'a':0})


# 地址管理
def dzgl(request):
    # 获取当前用户
    user = models.Users.objects.get(id=request.session['vipUser']['uid'])
    
    context = {'user':user}
    # 加载模板
    return render(request,'home/dzgl.html',context)


# 用户管理
def yhgl(request):
    # 判断请求方式
    if request.method == 'GET':    
        # 根据uid获取用户对象
        ob = models.Users.objects.get(id=uid)
        # 显示编辑表单
        return render(request,'myadmin/users/edit.html',{'uinfo':ob})   
    
    elif request.method == 'POST':
        oa = request.POST.get('id')
        ob = models.Users.objects.get(id=oa)
        # # 执行编辑
        ob.username = request.POST.get('username')
        # 密码判断
        if request.POST.get('password'):
            # 修改
            ob.password = make_password(request.POST['password'], None, 'pbkdf2_sha256')

        ob.phone = request.POST.get('phone')

        ob.email = request.POST.get('email')

        ob.age = request.POST.get('age')

        ob.sex = request.POST.get('sex')
        # 判断是否更新了头像
        myfile = request.FILES.get('pic_url')
        
        if myfile:
            # 上传新头像,删除原头像
            if ob.pic_url != '/static/pics/user.jpg':
                try:
                    # 删除原来上传的主图
                    os.remove(BASE_DIR+ob.pic_url)
                except:
                    pass

            # 更新头像
            ob.pic_url = uploads(myfile)

        # 执行数据更新
        ob.save()
        return HttpResponse('<script>alert("更新成功");location.href="'+reverse('home_orderinfo')+'"</script>')
# location.href="'+reverse('myadmin_user_index')+'"

